package com.itheima.app.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 自定义拦截器
 * @author zsk
 * @create 2022-03-14-19:22
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserManager userManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取前端携带的token
        String token = request.getHeader("Authorization");
        //解析token
        User user = userManager.findUserByToken(token);
        //对user进行判断
        if(user == null){//未null表示未登录
            response.setStatus(401);//表示权限不足
            return false;//拦截
        }
        //将user对象放入ThreadLocal中
        UserHolder.set(user);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除User信息
        UserHolder.remove();
    }
}
